#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: gui.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  the gui class

import os
#import datetime
import Queue

import pynotify

import gobject
gobject.threads_init()
import gtk
gtk.gdk.threads_init()


from vazaarlib.ui.glade import Widgets
from vazaarlib.ui.topbar import MenuManager
from vazaarlib.ui.actions import ActionManager
from vazaarlib.ui.actionbar import ActionBarManager
from vazaarlib.ui.clipboard import ClipboardManager
from vazaarlib.ui.content import ContentManager
from vazaarlib.ui.icons import IconManager
from vazaarlib.ui.editor import ResourceEditor
from vazaarlib.ui.collectionview import CollectionView
from vazaarlib.ui.clipboardview import ClipboardView
from vazaarlib.ui.addresource import AddResourceDialog
from vazaarlib.ui.statusbar import StatusBarManager
from vazaarlib.ui.trayicon import VazaarStatusIcon
#from ui.toolbars import ToolbarResource
#from ui.toolbars import ToolbarMain
#from ui.widgets.genericlistview import GenericListView
#from ui.theme import ThemeManager
#from ui.timeouts import TimeOutsManager
#from ui.signals import SignalManager
#from ui.models import ModelManager
#from ui.events import EventManager
from vazaarlib.utils import get_logger
from vazaarlib.constants import GUI_DIR

class GUI:
    """ this is the GUI class, which is called in the main thread"""
    current = {}
    current['resources'] = {}
    settings = {}
    current['log'] = {}
    current['qend'] = Queue.Queue()
    property = {}
    frontend = {}
    model = {}
    queue = {}
    last_query = None
    

    def __init__(self, app, qin, qout, ask):
        """
        qin in a Queue.Queue that store jobs to be done
        qout is a Queue.Queue that store result of completed jobs
        The GuiPart is supposed to push stuff in qin ,and regularly check
        if new result are available in qout
        """
        self.app = app
        self.widget = gtk.Label('')
        self.frontend['target-res'] = [] # a list of target resources
        self.frontend['target-col'] = [] # a list of target collections
        self.frontend['cloud'] = None
        self.frontend['preferences'] = {}
        self.frontend['view'] = {}
        self.frontend['view']['current_resources'] = None
        self.frontend['view']['selected'] = None
        self.frontend['view']['previous'] = None
        self.frontend['view']['current'] = None
        self.queue['in'] = qin      # Incoming jobs
        self.queue['out'] = qout    # Outcoming jobs
        self.job_counter = 0
        self.current_job_id = None
        
        self.log = get_logger("Frontend")

        if not pynotify.init("Vazaar"):
            self.log.error('PyNotify not initialized')

        self.glade = Widgets(os.path.join(GUI_DIR, "vazaar.glade"))
        self.frontend['mainwin'] = self.glade.widgets.get_widget("winMain")
        self.property['visible'] = False
        self.property['working'] = False
        self.property['counter'] = 0
        self.menu       = MenuManager(self)         # MenuBar Manager
        self.statusbar  = StatusBarManager(self)    # StatusBar Manager
        self.actionbar  = ActionBarManager(self)    # ActionBar Manager
        self.actions    = ActionManager(self)       # Actions Manager
        self.trayicon   = VazaarStatusIcon(self)    # Tray Icon Manager
        self.icons      = IconManager(self)         # Icon Manager
        self.clipboard  = ClipboardManager(self)    # Clipboard Manager
        self.manager    = ContentManager(self)      # Content Manager
        self.ask        = ask                       # Query Manager
        self.colview    = CollectionView(self)
        self.clpview    = ClipboardView(self)
        self.editor     = ResourceEditor(self)
        self.addresdlg  = AddResourceDialog(self)
        #self.signals    = SignalManager(self)       # Signals Manager
        #self.models     = ModelManager(self)        # Models Manager
        #self.theme      = ThemeManager(self)        # Theme Manager
        #self.events     = EventManager(self)        # Events Manager
        self.frontend['mainwin'].connect('delete-event', self.actions.show_application)

        icon = self.icons.get_icon_by_name('Collection.svg')
        self.frontend['mainwin'].set_icon(icon)
        self.frontend['mainwin'].connect('delete-event', self.hide_main_window)
        self.frontend['mainwin'].connect('destroy', self.hide_main_window)

        #self.timeouts   = TimeOutsManager(self)     # Timeouts Manager
        self.log.info("Frontend initialized")

        # FIXME: Execute Wizard at first run of this program
        self.actions.first_run()

        # Execute everytimes vazaar is launched. Set up environment
        self.actions.every_runs()

        #gobject.timeout_add(1000, self.actions.check_incoming_jobs)
        #gobject.timeout_add(1000, self.actions.check_outcoming_jobs)
        self.statusbar.set_text("Hi there")

        self.timeout_handler = gobject.timeout_add(200, self.process_outcoming)



    def hide_main_window(self, *args):
        """ hide main window """

        return False

    def process_outcoming(self):
        """Handle all jobs currently in qout, if any"""
        #print len(self.app.vstore.vstore)
        #self.actions.update_statusbar("<i>waiting for new resources...</i>")
        #if self.current_job_id != None:
        #    id = str(self.current_job_id)

        if self.queue['in'].qsize() or self.current_job_id != None:
            message = self.app.get_message()
            fraction = self.app.get_fraction()
            percentaje = self.app.get_percentaje()
            self.statusbar.set_text(message)
            self.statusbar.update_progressbar(fraction, percentaje)
        else:
            #hide progressbar/statusbar
            pass

        while self.queue['out'].qsize():
            try:
                job = self.queue['out'].get(0)
                self.process_result(job)
            except Queue.Empty:
                self.statusbar.set_text("qout is empty")

        return True


    def process_result(self, job):
        """a new job has been processed, we have to display the result"""

        self.statusbar.set_text("Job[%d]: finished" % job.id)
        self.log.debug("Job[%d]: finished" % job.id)
        self.actions.update_gui()

        """
        if not self.queue['out'].qsize():
            now = datetime.datetime.now()
            last_update = now - self.last_query
            if last_update.seconds > 5:
                self.log.debug("Last query: %s (%d seconds ago). Updating GUI" % (self.last_query, last_update.seconds))
                self.app.vstore.update_real_store()
                self.actions.update_gui()
            else:
                self.log.debug("No GUI update needed")
        """


    def get_graph(self):
        """ get graph from store """

        return self.app.store.get_graph()


    def query_graph(self, query):
        """ send query to graph and get results """

        return self.app.store.do_query(query)

